#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include "flash_eeprom.h"

unsigned char block1[16 * 4 * 1024] = {0xff};

#define PRINTW(v, buf) printf("write "#v": %s\n", buf)
#define PRINTR(v, buf) printf("read "#v": %s\n", buf)
#define TEST(fun) do { \
                    int ret = fun; \
                    if (ret < 0) { \
                        printf ("test "#fun" failed: %d\n", ret); \
                    } \
                } while (0)

int main(int argc, char *argv[])
{
    TEST(flash_eeprom_init((uint32_t)block1, 1));
    
    uint32_t var1 = flash_eeprom_makeid("var1");
    uint32_t var2 = flash_eeprom_makeid("var2");
    uint32_t var3 = flash_eeprom_makeid("var3");
    uint32_t var4 = flash_eeprom_makeid("var4");
    
    printf("write flash .... \n");
    TEST(flash_eeprom_write(var1, "abcdef", sizeof("abcdef")));
    PRINTW(var1, "abcdef");
    TEST(flash_eeprom_write(var2, "ghij", sizeof("ghij")));
    PRINTW(var2, "ghij");
    TEST(flash_eeprom_write(var3, "klmnopqrst", sizeof("klmnopqrst")));
    PRINTW(var3, "klmnopqrst");
    TEST(flash_eeprom_write(var4, "uvwxyz", sizeof("uvwxyz")));
    PRINTW(var4, "uvwxyz");
    printf("\nread flash .... \n");
    uint8_t buff[1024];
    TEST(flash_eeprom_read(var1, buff, sizeof(buff)));
    PRINTR(var1, buff);
    TEST(flash_eeprom_read(var2, buff, sizeof(buff)));
    PRINTR(var2, buff);
    TEST(flash_eeprom_read(var3, buff, sizeof(buff)));
    PRINTR(var3, buff);
    TEST(flash_eeprom_read(var4, buff, sizeof(buff)));
    PRINTR(var4, buff);
    
    printf("write flash ....5 \n");
    int cnt = 5;
    for (int i = 0; i < 5; i++) {
        sprintf(buff, "abcdef%d", i);
        TEST(flash_eeprom_write(var1, buff, strlen(buff)));
        PRINTW(var1, buff);
        sprintf(buff, "klmno%dpqrst", i);
        TEST(flash_eeprom_write(var3, buff, strlen(buff)));
        PRINTW(var3, buff);
        sprintf(buff, "ab%dcdef", i);
        TEST(flash_eeprom_write(var4, buff, strlen(buff)));
        PRINTW(var4, buff);
    }
    
    printf("\nread flash .... \n");
    TEST(flash_eeprom_read(var1, buff, sizeof(buff)));
    PRINTR(var1, buff);
    TEST(flash_eeprom_read(var2, buff, sizeof(buff)));
    PRINTR(var2, buff);
    TEST(flash_eeprom_read(var3, buff, sizeof(buff)));
    PRINTR(var3, buff);
    TEST(flash_eeprom_read(var4, buff, sizeof(buff)));
    PRINTR(var4, buff);
    
    return 0;
}
